//
//  RenWuViewController.m
//  ShouYi
//
//  Created by yurui on 16/2/18.
//  Copyright © 2016年 yurui. All rights reserved.
//

#import "RenWuViewController.h"
#import "ContentTableViewCell.h"
#import "DetailViewController.h"
#import "RenWuHeaderView.h"

#import "TaskClassListModel.h"
#import "TaskListModel.h"
@interface RenWuViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong) RenWuHeaderView *headerView;

@property(nonatomic,strong) NSString *dataType;

@property (nonatomic,strong)NSMutableArray *TaskClassArray;
// 任务(全国)
@property (nonatomic,strong)NSMutableArray *TaskListArray;
// 任务(本地)
@property (nonatomic,strong)NSMutableArray *bendiListArray;
@property (nonatomic)int titleNumber;
@property (nonatomic,strong)UIScrollView *scrollView;
@property (nonatomic,strong)UIPageControl *pageControl;
@property(nonatomic,strong) UITableView *tableView;

@end

@implementation RenWuViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    
    //刚进来重置数据类型
    self.dataType = @"全国";
    //刚进来设置标题位置
    self.titleNumber = 0;
    
    [self addHeaderView];
    //添加标题滑动
  //  [self addScrollView];
    
    [self setUpDataForTaskClass];
    [self configerTableView];
    
}
// 头部View
- (void)addHeaderView{
    self.headerView = [[RenWuHeaderView alloc]initWithFrame:CGRectMake(0, 0,kWidth , 64)];
    self.headerView.backgroundColor = kBackGroundColor;
    [self.view addSubview:_headerView];
    
    [self.headerView.searchBt addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.countryBt addTarget:self action:@selector(countryData) forControlEvents:UIControlEventTouchUpInside];
    
    [self.headerView.benDiBt addTarget:self action:@selector(benDiData) forControlEvents:UIControlEventTouchUpInside];
    
    [self.headerView.messageBt addTarget:self action:@selector(messageAction) forControlEvents:UIControlEventTouchUpInside];
}

// 添加滚动条目
- (void)addScrollView{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, kWidth, 44)];
    self.scrollView.contentSize = CGSizeMake(kWidth / 5 * self.TaskClassArray.count, 44);
   self.scrollView.backgroundColor = [UIColor colorWithRed:235.0/255 green:235.0/255 blue:235.0/255 alpha:1];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    for (int i =0; i < self.TaskClassArray.count; i ++) {
        UIButton *titleBt = [[UIButton alloc]initWithFrame:CGRectMake(kWidth / 5 * i, 0, kWidth / 5, 44)];
        titleBt.titleLabel.font = [UIFont systemFontOfSize:15];
        [titleBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        // 分类数组(全国)
        NSMutableArray *tempArray = [NSMutableArray array];
        [self.TaskListArray addObject:tempArray];
        // 分类数组(本地)
        NSMutableArray *bendiArray = [NSMutableArray array];
        [self.bendiListArray addObject:bendiArray];
        
        TaskClassListModel *model = self.TaskClassArray[i];
        [titleBt setTitle:model.classname forState:UIControlStateNormal];
        titleBt.tag = 1000 + i;
        [titleBt addTarget:self  action:@selector(titleAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:titleBt];
        
        if (i == 0) {
            [titleBt setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
            titleBt.titleLabel.font = [UIFont systemFontOfSize:17];
        }
        
    }
    
    [self.view addSubview:self.scrollView];
    
    //添加完解析任务列表
    [self setUpDataForTaskList];
    
}
// 配置tableView
- (void) configerTableView{
    
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,108, kWidth, kHeight - 160)];
        self.tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        self.tableView.tag = 3000;
        _tableView.dataSource = self;
    
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            NSLog(@"下拉加载");
            
            [self setUpDataForTaskListJIAZAI];
            
        }];
        
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            NSLog(@"上拉刷新");
            
            [self setUpDataForTaskList];
            
        }];

        [self.tableView registerClass:[ContentTableViewCell class] forCellReuseIdentifier:@"cell"];
        [self.view addSubview:_tableView];
}


// 搜索按钮事件
- (void)searchAction{
    self.hidesBottomBarWhenPushed = YES;
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
// 全国按钮事件
- (void)countryData{
    self.headerView.imageV.image = [UIImage imageNamed:@"icon_qg.png"];
    self.dataType = @"全国";
    
    [self setUpDataForTaskList];
    
    [self.tableView reloadData];
    
    
    
    
    
}
// 本地按钮事件
- (void)benDiData{
    self.headerView.imageV.image = [UIImage imageNamed:@"icon_qg_1.png"];
    self.dataType = @"本地";
    [self setUpDataForTaskList];
    [self.tableView reloadData];
}
// 信息按钮事件
- (void)messageAction{
    self.hidesBottomBarWhenPushed = YES;
    MessageViewController *searchVC = [[MessageViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

// 滑动标题响应事件
- (void)titleAction:(UIButton *)sender{
    
    for (int i = 1000;  i < self.TaskClassArray.count + 1000; i ++) {
        UIButton *bt = [self.scrollView viewWithTag:i];
        NSMutableArray *arr = [NSMutableArray array];
        [arr addObject:bt];
        // 遍历所有button  使其颜色变为黑色
        for (UIButton *bb in arr) {
            [bb setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        // 点击哪个button 使其颜色变为红色  其他的不变
        if (i == sender.tag ) {
            [bt setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            bt.titleLabel.font = [UIFont systemFontOfSize:17];
        }else{
            [bt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            bt.titleLabel.font = [UIFont systemFontOfSize:15];
        }
    }
    
    //点击标题横条 移动标题
    self.titleNumber = (int)sender.tag - 1000;
    if (self.titleNumber == 0) {
        
        
    }else if( self.TaskClassArray.count - self.titleNumber > 4) {
        
        [self.scrollView setContentOffset:CGPointMake(kWidth / 5 * (self.titleNumber - 1), 0) animated:YES];
    }else {
        [self.scrollView setContentOffset:CGPointMake(kWidth / 5 * self.TaskClassArray.count - kWidth, 0) animated:YES];
    }
    
    [self setUpDataForTaskList];
    [self.tableView setContentOffset:CGPointMake(0, 0)];
    NSLog(@"%@",sender.titleLabel.text);
}


#pragma mark --- 数据处理 ---
- (NSMutableArray *)TaskClassArray {
    if (!_TaskClassArray) {
        _TaskClassArray = [NSMutableArray array];
    }
    return _TaskClassArray;
}
//全国
- (NSMutableArray *)TaskListArray {
    if (!_TaskListArray) {
        _TaskListArray = [NSMutableArray array];
    }
    return _TaskListArray;
}
//本地
- (NSMutableArray *)bendiListArray {
    if (!_bendiListArray) {
        _bendiListArray = [NSMutableArray array];
    }
    return _bendiListArray;
}

//解析任务分类
- (void)setUpDataForTaskClass {
    
    [LORequestManger GET:KTaskClassList success:^(id response) {
        
        NSLog(@"测试");
        
        NSArray *array = (NSArray *)response;
        for (NSDictionary *dic in array) {
            TaskClassListModel *model = [TaskClassListModel setUpDic:dic];
            [self.TaskClassArray addObject:model];
        }
        
        [self addScrollView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];

}
//任务列表(上拉刷新)
- (void)setUpDataForTaskList {
    
    NSString *strIP = [[NSUserDefaults standardUserDefaults] objectForKey:@"IP"];
    
    
    TaskClassListModel *model = self.TaskClassArray[self.titleNumber];

    NSMutableArray *tempArray = [NSMutableArray array];
    
    if ([self.dataType isEqualToString:@"全国"]) {
        tempArray = self.TaskListArray[self.titleNumber];
    }else {
        tempArray = self.bendiListArray[self.titleNumber];
    }
    
    
    if (tempArray.count == 0) {
//当对应的任务数组中没有数据刷新时
        NSString *url = [KTaskList stringByAppendingString:[NSString stringWithFormat:@"&cid=%@",model.classid]];
//区分全国和本地
        if ([self.dataType isEqualToString:@"全国"]) {
            url = [url stringByAppendingString:@"&localtype=0"];
        }else {
             url = [url stringByAppendingString:[NSString stringWithFormat:@"&localtype=1&userip=%@",strIP]];
            
        }
    
        
        NSLog(@"%@",url);
        
        [SVProgressHUD show];
        
        [LORequestManger GET:url success:^(id response) {
            
            //分类标题对应的数组
            NSArray *arry = (NSArray *)response;
            for (NSDictionary *dic in arry) {
                TaskListModel *model = [TaskListModel setUpDic:dic];
                [tempArray addObject:model];
            }
            //赋值完 替换任务列表数组 && 区分全国和本地
            if ([self.dataType isEqualToString:@"全国"]) {
                [self.TaskListArray replaceObjectAtIndex:self.titleNumber withObject:tempArray];
            }else {
                [self.bendiListArray replaceObjectAtIndex:self.titleNumber withObject:tempArray];
            }
            [self.tableView reloadData];
        
            [SVProgressHUD dismiss];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
            
            [SVProgressHUD dismiss];
            
        }];
    }else {
        
       // NSMutableArray *tempArray = self.TaskListArray[self.titleNumber];
        
        TaskListModel *lastModel = tempArray.firstObject;
        
        NSString *url = [KTaskList stringByAppendingString:[NSString stringWithFormat:@"&cid=%@&nextid=%@",model.classid,lastModel.ID]];
        
        //区分全国和本地
        if ([self.dataType isEqualToString:@"全国"]) {
            url = [url stringByAppendingString:@"&localtype=0"];
        }else {
            url = [url stringByAppendingString:[NSString stringWithFormat:@"&localtype=1&userip=%@",strIP]];
        }

        NSLog(@"%@",url);

        [LORequestManger GET:url success:^(id response) {
            
            //临时数据存储刷新出来的数据
            NSMutableArray *emptyArray = [NSMutableArray array];
            NSArray *array = (NSArray *)response;
            //赋值刷新出来的数据
            for (NSDictionary *dic in array) {
                TaskListModel *model = [TaskListModel setUpDic:dic];
                [emptyArray addObject:model];
            }
            //将原数组中的数据添加到临时数组中
            for (TaskListModel *TModel in tempArray) {
                [emptyArray addObject:TModel];
            }
            //清空原数组,并把临时数组替换原数组
            [tempArray removeAllObjects];
            for (TaskListModel *tempModel in emptyArray) {
                [tempArray addObject:tempModel];
            }
            //赋值完 替换任务列表数组 && 区分全国和本地
            if ([self.dataType isEqualToString:@"全国"]) {
                [self.TaskListArray replaceObjectAtIndex:self.titleNumber withObject:tempArray];
            }else {
                [self.bendiListArray replaceObjectAtIndex:self.titleNumber withObject:tempArray];
            }
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            
            [SVProgressHUD dismiss];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            NSLog(@"%@",error);
            [self.tableView.mj_header endRefreshing];
            [SVProgressHUD dismiss];
            
        }];


        [self.tableView reloadData];
        
    }
}

//任务列表(下拉加载)
- (void)setUpDataForTaskListJIAZAI {
    
    TaskClassListModel *model = self.TaskClassArray[self.titleNumber];
    
    //分类标题对应的数组
    NSMutableArray *tempArray = self.TaskListArray[self.titleNumber];
    TaskListModel *lastModel = tempArray.lastObject;
    
    NSString *url = [KTaskList stringByAppendingString:[NSString stringWithFormat:@"&cid=%@&preid=%@",model.classid,lastModel.ID]];
    
    NSLog(@"%@",url);
    [SVProgressHUD show];
    [LORequestManger GET:url success:^(id response) {
        NSArray *arry = (NSArray *)response;
        
        for (NSDictionary *dic in arry) {
            TaskListModel *model = [TaskListModel setUpDic:dic];
            [tempArray addObject:model];
        }
        //赋值完 替换任务列表数组
        [self.TaskListArray replaceObjectAtIndex:self.titleNumber withObject:tempArray];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        
        [SVProgressHUD dismiss];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD dismiss];
        [self.tableView.mj_footer endRefreshing];
        [self showAlertMessage:@"没有更多内容"];
    }];
    
}

#pragma  mark UITableViewDelegate 和UITableViewDataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([self.dataType isEqualToString:@"全国"]) {
        
        if (self.TaskListArray.count != 0) {
            NSArray *array = self.TaskListArray[self.titleNumber];
            return array.count;
        }
        
    }else {
#pragma mark --- 写到这了 ----
        if (self.bendiListArray.count != 0) {
            NSArray *array = self.bendiListArray[self.titleNumber];
            return array.count;
        }

    }

    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    NSArray *modelArray = [NSMutableArray array];
    
    if ([self.dataType isEqualToString:@"全国"]) {
        modelArray = self.TaskListArray[self.titleNumber];
    }else {
        modelArray = self.bendiListArray[self.titleNumber];
    }
    
    
    if (modelArray.count > 0) {
        TaskListModel *model = modelArray[indexPath.row];
            [cell setModelForTaskList:model];
        }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.hidesBottomBarWhenPushed = YES;
    
    NSArray *modelArray = self.TaskListArray[self.titleNumber];
    if (modelArray.count > 0) {
        TaskListModel *model = modelArray[indexPath.row];
        DetailViewController *detailVC = [[DetailViewController alloc] init];
        detailVC.webUrl = model.gourl;
        detailVC.imagesrc = model.imgsrc;
        detailVC.title = model.title;
        [self.navigationController pushViewController:detailVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//滑动结束触发
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
}

#pragma mark --- 提醒视图 ---
//添加 收藏提醒框图
- (void)showAlertMessage:(NSString *)message {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"通知" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    [self performSelector:@selector(dimissAlert:) withObject:alert afterDelay:1];
    
}

// 提醒视图消失
- (void)dimissAlert:(UIAlertView *)alert {
    
    if (alert) {
        [alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
